//
//  RegisterViewController.m
//  WorkNest
//
//  Created by qbm360 on 15/7/6.
//  Copyright (c) 2015年 nest. All rights reserved.
//

#import "RegisterViewController.h"
#import "CustomTabBarViewController.h"
#import "AgreementViewController.h"

@interface RegisterViewController () <UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *phoneNumberText;
@property (weak, nonatomic) IBOutlet UITextField *codeNumberText;
@property (weak, nonatomic) IBOutlet UITextField *passwordText;
@property (weak, nonatomic) IBOutlet UITextField *repeatPasswordText;
@property (weak, nonatomic) IBOutlet UIButton *agreeButton;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;
@property (weak, nonatomic) IBOutlet UIButton *requestCodeButton;
@property (weak, nonatomic) IBOutlet UITextField *recommended;
@property (assign, nonatomic) BOOL ifAgreeButtonSelected;
@property (weak, nonatomic) IBOutlet UIButton *buyerButton;
@property (weak, nonatomic) IBOutlet UIButton *designerButton;

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _ifAgreeButtonSelected = YES;
    _agreeButton.selected = YES;
    self.phoneNumberText.delegate = self;
    self.codeNumberText.delegate = self;
    self.passwordText.delegate = self;
    self.repeatPasswordText.delegate = self;
    self.recommended.delegate = self;

    self.title = NSLocalizedString(@"注册", nil);
    [UIUtil configTextField:_phoneNumberText withTitle:@""];
    [UIUtil configTextField:_codeNumberText withTitle:@""];
    [UIUtil configTextField:_passwordText withTitle:@""];
    [UIUtil configTextField:_repeatPasswordText withTitle:@""];
    [UIUtil configTextField:_recommended withTitle:@""];
    [_phoneNumberText addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.buyerButton.selected = YES;
    self.navigationItem.rightBarButtonItem = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Action Methods
- (IBAction)requestCodeButton:(id)sender {
    _requestCodeButton.enabled = NO;
    NSDictionary *dic = @{@"userName":_phoneNumberText.text, @"systemId":systemId, @"codeType":@"1", @"userNameType": @"1"};
    
    [RequestData getCodeNumber:[UIUtil toJsonString:dic] withBlock:^(NSString *msg, NSError *error) {
        if (error) {
            [[ESHUDView sharedInstance] showErrorMessage:msg == nil?@"获取验证码失败":msg dismissBlock:nil];
        } else {
            [[ESHUDView sharedInstance] showSuccessMessage:msg dismissBlock:nil];
        }
    }];
    __block int timeout = 60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [_requestCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                _requestCodeButton.enabled = YES;
            });
        }else{
            int seconds = timeout % 181;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                [_requestCodeButton setTitle:[NSString stringWithFormat:@"%@秒后重发",strTime] forState:UIControlStateNormal];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

- (IBAction)agreementButton:(id)sender {
    _ifAgreeButtonSelected = !_ifAgreeButtonSelected;
    _agreeButton.selected = _ifAgreeButtonSelected;
}

- (IBAction)registerButton:(id)sender {
    [self.view endEditing:YES];
    if ([_phoneNumberText.text isEqualToString:@""] || [_passwordText.text isEqualToString:@""] || [_repeatPasswordText.text isEqualToString:@""] || [_codeNumberText.text isEqualToString:@""]) {
        [[ESHUDView sharedInstance] showErrorMessage:@"用户名,验证码,密码或推荐人不能为空" dismissBlock:nil];
        return;
    }
    if (![_passwordText.text isEqualToString:_repeatPasswordText.text]) {
        [[ESHUDView sharedInstance] showErrorMessage:@"两次密码不一致" dismissBlock:nil];
        return;
    }
    if (!_ifAgreeButtonSelected) {
        [[ESHUDView sharedInstance] showErrorMessage:@"您没有同意衣联用户服务协议" dismissBlock:nil];
        return;
    }
    _registerButton.enabled = NO;
    
    NSDictionary *loginParam = @{@"userName":_phoneNumberText.text, @"password":_passwordText.text, @"advisor":_recommended.text, @"systemId":systemId, @"authCode":_codeNumberText.text, @"userType":_buyerButton.selected?@"1":@"2", @"deviceId":[[NSUUID UUID] UUIDString]};
    [RequestData registParameters:[UIUtil toJsonString:loginParam] withBlock:^(UserModel *userData, NSString *msg, NSError *error) {
        if (error) {
            [[ESHUDView sharedInstance] showErrorMessage:msg == nil?@"注册失败":msg dismissBlock:nil];
            _registerButton.enabled = YES;
        } else {
            [[ESHUDView sharedInstance] showSuccessMessage:msg dismissBlock:nil];
            [[UserModel sharedInstance] setUserToken:userData.userToken];
            [[UserModel sharedInstance] setUserName:userData.userName];
            CustomTabBarViewController *tabBarView = [[CustomTabBarViewController alloc] init];
            self.view.window.rootViewController = tabBarView;
            [self.view.window addSubview: tabBarView.view];
            [self.view removeFromSuperview];
            }
        }];

}

- (IBAction)protocolButton:(id)sender {
    AgreementViewController *view = [[AgreementViewController alloc] init];
    [self.navigationController pushViewController:view animated:YES];
}

- (IBAction)buyerButton:(id)sender {
    self.buyerButton.selected = YES;
    self.designerButton.selected = NO;
}

- (IBAction)designerButton:(id)sender {
    self.buyerButton.selected = NO;
    self.designerButton.selected = YES;
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == _phoneNumberText) {
        [_codeNumberText becomeFirstResponder];
        return YES;
    }
    if (textField == _codeNumberText) {
        [_passwordText becomeFirstResponder];
        return YES;
    }
    if (textField == _passwordText) {
        [_passwordText becomeFirstResponder];
        return YES;
    }
    if (textField == _repeatPasswordText) {
        [_repeatPasswordText becomeFirstResponder];
        return YES;
    }
    if (textField == _recommended) {
        [_recommended resignFirstResponder];
        return YES;
    }
    return NO;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)textFieldDidChange:(UITextField *)textField {
    if (textField == self.phoneNumberText) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }
    if (textField == self.codeNumberText) {
        if (textField.text.length > 6) {
            textField.text = [textField.text substringToIndex:6];
        }
    }
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    textField.inputAccessoryView = view;
    view.backgroundColor = [UIColor whiteColor];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(SCREEN_WIDTH - 40, 0, 40, 30);
    [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [btn setTitle:@"完成" forState: UIControlStateNormal];
    [btn addTarget:self action:@selector(checkButton) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    [textField reloadInputViews];
    return YES;
}

- (void)checkButton {
    [self.view endEditing:YES];
}

@end
